package org.lex.ftp.net.find;

import java.io.IOException;

import org.lex.net.ftp.IFTPClient;
import org.lex.net.ftp.IFTPFile;
import org.lex.utils.tree.AbstractNode;
import org.lex.utils.tree.Node;


public class FTPFileNode extends AbstractNode {
	private static final FTPFileNode[] EMPTY = new FTPFileNode[0];
	private final IFTPClient ftp;
	private FTPFileNode[] children = EMPTY;
	private boolean loaded = false;
	private IFTPFile file = null;

	public FTPFileNode(IFTPClient ftp, IFTPFile file) {
		super(file);
		this.ftp = ftp;
		this.file = file;
	}

	@Override
	public IFTPFile getData() {
		return file;
	}

	public Node getChildAt(int index) {
		if (false == loaded)
			this.loadChildren();
		return children[index];
	}

	public int getChildCount() {
		if (false == loaded)
			this.loadChildren();
		return children.length;
	}

	private void loadChildren() {
		this.loaded = true;
		if (false == this.file.isDirectory())
			// file
			return;
		// folder
		IFTPFile[] files = null;
		try {
			ftp.cwd(file.getFullPath());
			files = ftp.list();
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		this.children = new FTPFileNode[files.length];
		for (int i = 0; i < files.length; i++)
			children[i] = new FTPFileNode(ftp, files[i]);
	}
}
